package com.awesome.spring.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.awesome.spring.fallback.SentinelControllerFallback;
import com.awesome.spring.fallback.SentinelControllerBlockHandler;
import com.awesome.spring.service.SentinelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * SentinelController
 *
 * @author alex wu
 * @date 2023/10/08
 */
@RequestMapping("/sentinel")
@RestController
public class SentinelController {

    @Autowired
    private SentinelService sentinelService;

    @SentinelResource(value = "user-name-resource", blockHandler = "userNameHandler", fallback = "userNameFallback")
    @GetMapping("/userName")
    public String userName() {
        return sentinelService.userName();
    }

    public String userNameHandler(BlockException ex) {
        // Do some log here.
        ex.printStackTrace();
        return "Oops, error occurred at ";
    }

    public String userNameFallback(String name) {
        return String.format("Halooooo %d", name);
    }

    @SentinelResource(value = "user-age-resource", blockHandlerClass = SentinelControllerBlockHandler.class, blockHandler = "userAgeBlockHandler")
    @GetMapping("/userAge")
    public String userAge() {
        return sentinelService.userAge();
    }

//    @SentinelResource(value = "user-addr-resource", fallbackClass = SentinelControllerFallback.class, blockHandler = "userAgeBlockHandler", fallback = "userAddrFallback")
//    @GetMapping("/userAddr")
//    public String userAddr() {
//        return sentinelService.userAddr();
//    }

    /**
     * 使用全局异常处理，识别熔断降级
     * @return
     */
//    @SentinelResource(value = "user-addr-resource")
//    @GetMapping("/userAddr")
//    public String userAddr() {
//        return sentinelService.userAddr();
//    }

    @SentinelResource(value = "user-addr-resource", fallbackClass = SentinelControllerFallback.class, fallback = "userAddrFallback")
    @GetMapping("/userAddr")
    public String userAddr() {
        return sentinelService.userAddr();
    }

}
